<template>
  <div>
    <el-card class="!border-none" shadow="never">
      <el-page-header
        content="直播编辑"
        @back="$router.back()"
      />
    </el-card>
    <el-card class="!border-none mt-4" shadow="never">
      <el-tabs v-model="active" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="内容编辑" name="content">
          <el-form
                  class="your-form-class"
                  label-width="150px"
                  ref="formRef"
                  :model="editForm"
                  :rules="rulesContent"
          >
            <el-form-item label="直播间名称" prop="name" class="max-w-[300px]">
              <el-input v-model="editForm.name" placeholder="请输入等级名称" />
            </el-form-item>
            <el-form-item label="直播间封面" prop="cover">
              <div class="flex flex-col gap-2">
                <el-image style="width: 100px; height: 100px" :src="editForm.cover" />
                <upload
                        class="mr-3"
                        :type="'image'"
                        :show-progress="true"
                        @change="actionImg"
                        ref="myref"
                >
                  <el-button type="primary">本地上传</el-button>
                </upload>
              </div>
<!--              <el-upload-->
<!--                      v-model:file-list="fileList"-->
<!--                      action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"-->
<!--                      list-type="picture-card"-->
<!--                      :on-preview="handlePictureCardPreview"-->
<!--                      :on-remove="handleRemove"-->
<!--              >-->
<!--                <el-icon><Plus /></el-icon>-->
<!--              </el-upload>-->
<!--              <material-picker :limit="1" v-model="editForm.cover" />-->
            </el-form-item>
            <el-form-item label="开播时间" prop="start_time" >
              <el-date-picker
                      v-model="editForm.start_time"
                      type="datetime"
                      placeholder="请选择开播时间"
                      value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <div style="display: flex; gap: 10px">
              <el-form-item label="直播形式" prop="is_record_mode" >
                <el-radio-group v-model="editForm.is_record_mode">
                  <el-radio :label="0">正常直播</el-radio>
                  <el-radio :label="1">录播</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="editForm.is_record_mode == 1" label="选择录播视频" prop="coupon_id">
                <el-select placeholder="无" v-model="editForm.record_mode_video_id">
                  <el-option
                          v-for="item in videoList"
                          :label="item.record_mode_video_name"
                          :value="item.record_mode_video_id"
                          :key="item.record_mode_video_id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="直播样式" prop="live_style" >
              <el-radio-group v-model="editForm.live_style">
                <el-radio :label="0">横屏</el-radio>
                <el-radio :label="1">竖屏</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否生成回放" prop="auto_record">
              <el-radio-group v-model="editForm.auto_record">
                <el-radio :label="0">不生成</el-radio>
                <el-radio :label="1">生成</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="主播间描述" prop="introduction">
              <el-input class="w-[400px]" v-model="editForm.introduction" type="textarea"  :autosize="{ minRows: 10, maxRows: 20 }" placeholder="请输入主播间描述" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品管理" name="goods">
          <CutPop ref="goodRef"></CutPop>
        </el-tab-pane>
        <el-tab-pane label="奖励设置" name="award">
          <el-form
                  ref="awardFormRef"
                  :rules="rulesAward"
                  :label-position="'right'"
                  :model="awardForm"
          >
            <el-form-item label="签到类型" prop="sign_switch">
              <el-radio-group v-model="awardForm.sign_switch">
                <el-radio :label="1">自动签到</el-radio>
                <el-radio :label="2">手动签到</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="自动签到发放奖励" prop="sign_reward_switch">
              <el-radio-group v-model="awardForm.sign_reward_switch">
                <el-radio :label="1">依据下方设置发放</el-radio>
                <el-radio :label="2">依据消费等级发放</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="观看多久直播自动签到 / 分钟" prop="look_time">
              <el-input-number v-model="awardForm.look_time" :min="1" :step="1"/>
            </el-form-item>
<!--            <el-form-item label="签到奖励礼品券数量" prop="reward_balance2">-->
<!--              <el-input-number v-model="awardForm.reward_balance2" :min="0" :step="1"/>-->
<!--            </el-form-item>-->
           <div>
             <el-form-item label="赠送选项" prop="red_switch">
               <el-radio-group v-model="awardFormType">
                 <el-radio :label="1">现金红包</el-radio>
                 <el-radio :label="2">优惠券</el-radio>
                 <el-radio :label="3">不发放奖励</el-radio>
               </el-radio-group>
             </el-form-item>
             <template v-if="awardFormType == 1">
               <el-form-item label="红包模式" prop="red_status_module">
                 <el-radio-group v-model="awardForm.red_status_module">
                   <el-radio :label="1">固定金额</el-radio>
                   <el-radio :label="2">随机金额</el-radio>
                 </el-radio-group>
               </el-form-item>
               <el-form-item label="固定红包金额" prop="red_price">
                 <el-input-number v-model="awardForm.red_price" :precision="2" :min="0"/>
               </el-form-item>
             </template>
             <template v-if="awardFormType == 2">
               <el-form-item label="赠送优惠券" prop="coupon_s_id">
                 <el-select v-model="awardForm.coupon_s_id"  clearable>
                   <template v-for="(item, index) in couponSelectList.list">
                     <el-option :label="item.name" :value="item.id" />
                   </template>
                 </el-select>
               </el-form-item>
               <el-form-item label="赠送优惠券数量" prop="look_time">
                 <el-input-number v-model="awardForm.coupon_num" :min="1" :step="1"/>
               </el-form-item>
             </template>
           </div>
<!--            <el-form-item label="签到红包" prop="red_switch">-->
<!--              <el-radio-group v-model="awardForm.red_switch">-->
<!--                <el-radio :label="1">开启</el-radio>-->
<!--                <el-radio :label="2">不开启</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="点名奖励设置" name="sign">
          <signPopup ref="signRef"/>
        </el-tab-pane>
      </el-tabs>
      <footer-btns v-perms="['goods.goods/edit', 'goods.goods/add']" v-if="['goods', 'sign'].indexOf(active) == -1 ">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </footer-btns>
    </el-card>
  </div>
</template>
<script lang="ts" setup>
import { rulesContent, rulesGood, rulesAward } from "./data";
import type { CheckboxValueType, ElTree, FormInstance } from "element-plus";
import type { TabsPaneContext } from 'element-plus'
import { useDictOptions } from "@/hooks/useDictOptions";
import {addRoomMz, editRoomMz, detailRoomMz, addRewardRoomMz, detailRewardRoomMz, getVideoList} from '@/api/live'
import useAppStore from "@/stores/modules/app";
import {reactive, ref} from "vue";
import { getCouponList } from "@/api/consumer";
import  CutPop from "./component/CutPop.vue";
import signPopup from './component/sign.vue'


const appStore = useAppStore();
const route = useRoute();
const router = useRouter();
const contentRef = shallowRef<FormInstance>();  // 内容编辑
const goodRef = shallowRef<FormInstance>(); // 商品管理
const awardFormRef = shallowRef<FormInstance>(); // 奖励设置
const signRef = shallowRef<FormInstance>(); // 点名奖励设置
const room_id = route.query?.id;
const myref = ref(null)

const active = ref("content");

const couponSelectList = ref([]);
// const { optionsData: couponList } = useDictOptions<{
//   lists: any[]
// }>({
//   lists: {
//     api: getCouponList
//   }
// });

getCouponList().then(res => {
  res.list?.unshift({
    id: 0,
    name: '---- 不选择 ----'
  })
  couponSelectList.value = res;
})



const videoList = ref([]);
getVideoList({
  page: 1,
  limit: 9999999
}).then(res => {
  videoList.value = [{
    record_mode_video_id: '0',
    record_mode_video_name: '暂无选择视频'
  }, ...res.list]
});


// 编辑内容
const editForm = reactive({
  room_id: room_id,
  channel_id: '',
  name: '',
  cover: '',
  start_time: '',
  live_style: '',
  auto_record: '',
  introduction: '',
  record_mode_video_id: 0,
  is_record_mode: 0,
});


// 照片更新
const actionImg = async (res) => {
  editForm.cover = myref.value.fileList[0].response.data.url;
};

// 直播间详情
detailRoomMz({
  room_id: room_id,
}).then(res => {
  if (res.info) {
    for (const key in editForm) {
      if (res.info.hasOwnProperty(key)) {
        editForm[key] = res.info[key];
      }
      if (key === 'record_mode_video_id') {
        editForm.record_mode_video_id = String(editForm.record_mode_video_id)
      }
      if (key === 'is_record_mode') {
        editForm.is_record_mode = Number(editForm.is_record_mode)
      }
    }
  }
});



//选择框数据
// const { optionsData } = useDictOptions<{
//   catelists: any[];
//   UnitList: any[];
// }>({
//   catelists: {
//     api: getGoodsCategory,
//   },
//   UnitList: {
//     api: getUnitList,
//   },
// });

// 商品管理
// const goodsFormData = reactive({
//   uuid: '',
//   coupon_id: [],
//   count: "",
// });
//
// const goodsList = [
//   {
//     id:0,
//     name: '测试商品1'
//   },
//   {
//     id:1,
//     name: '测试商品2'
//   }
// ];



// 奖励设置
const awardForm = reactive({
  room_id: room_id,
  sign_switch: 1,  // 签到类型 1 自动签到 2 手动签到
  sign_reward_switch: 1,  // 发放奖励模式 1 下方设置 2 消费等级
  look_time: 0,
  reward_balance2: 0,
  coupon_s_id: 0,
  red_switch: 1, // 签到积分 1 开启 2 关闭
  red_status_module: 1,  // 积分模式 1 固定金额 2 随机金额
  red_price: 0,
  coupon_num: 0, //  优惠券数量
});

// 奖励设置
const awardFormType = ref(1); // 1 现金红包  2 优惠券  3 不发放奖励

// 奖励详情
detailRewardRoomMz({
  room_id: room_id,
}).then(res => {
  for (const key in awardForm) {
    if (res.info) {
      if (res.info.hasOwnProperty(key)) {
        if (key === 'red_price') {
          awardForm[key] = Number(res.info[key]);
        } else {
          awardForm[key] = res.info[key];
        }


        if (res.info?.red_status_module == 1 && res.info?.red_price != 0) {
          awardFormType.value = 1
        }
        if (res.info?.coupon_s_id) {
          awardFormType.value = 2
        }
        if (res.info?.red_status_module == 1 && res.info?.red_price == 0 && !res.info?.coupon_s_id) {
          awardFormType.value = 3
        }

      }
    }
  }
});

watch(awardFormType,(newVal,oldVal)=>{
  if (newVal == 1) {
    awardForm.coupon_s_id = 0
  }
  if (newVal == 2) {
    awardForm.red_status_module = 1;
    awardForm.red_price = 0;
  }
  if (newVal == 3) {
    awardForm.coupon_s_id = 0
    awardForm.red_status_module = 1;
    awardForm.red_price = 0;
  }
})


const handleClick = (tab: TabsPaneContext, event: Event) => {
  switch (tab.props.name) {
    case 'content':  // 内容编辑
      break;
    case 'goods':  // 商品管理
      goodRef.value?.setFormData(room_id);
      break;
    case 'sign':  // 奖励设置
      signRef.value?.setFormData(room_id);
      break;
    default:
      break;
  }
}

const handleSubmit = async () => {
  switch (active.value) {
    case 'content':  // 内容编辑
      await contentRef.value?.validate();
      await editRoomMz(editForm);
      router.back();
      break;
    case 'goods':  // 商品管理
      // goodRef.value?.setFormData(room_id);
      break;
    case 'award':  // 奖励设置
      await awardFormRef.value?.validate();
      await addRewardRoomMz(awardForm);
      router.back();
      break;
    default:
      break;
  }
};
</script>
<style lang="scss" scope>
.preview {
  width: 375px;
  box-sizing: border-box;
  flex: none;
  height: 722px;
  border: 1px solid hsla(0, 0%, 89.8%, 0.898039);
  display: flex;
  flex-direction: column;
}
.title {
  background: #f5f8ff;
  height: 40px;
  border-bottom: 1px solid hsla(0, 0%, 89.8%, 0.898039);
}
.text-nowrap {
  word-break: break-all;
}
</style>
